﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;

namespace AdbRegisterUtils
{


    /// <summary>
    /// 重构后的 AdbService，使用 LogcatCaptureService
    /// </summary>
    public class AdbService : IDisposable
    {
        private static string _adbPath;
        private static string _commandR = "adb shell setprop vendor.extcamera.xxw.ispregctrl";
        private static string _commandMainSwitchS = "adb shell setprop vendor.extcamera.xxw.ispdebug 1";
        private static string _commandMainSwitchE = "adb shell setprop vendor.extcamera.xxw.ispdebug 0";
        private static string _commandLog = "adb shell logcat | findstr \"xmh\"";

        // 使用新的日志捕获服务
        private LogcatCaptureService _logcatService;
        private bool _isWant = false;

        public AdbService(string adbPath, bool debugMode = false)
        {
            _adbPath = adbPath;

            // 初始化日志捕获服务
            _logcatService = new LogcatCaptureService(_adbPath, _commandLog, debugMode);

            // 订阅事件
            _logcatService.OnLogReceived += OnLogReceived;
            _logcatService.OnError += OnError;
            _logcatService.OnStatusChanged += OnStatusChanged;
        }

        #region 事件处理
        private void OnLogReceived(LogcatModel log)
        {
            Console.WriteLine($"[EVENT] 收到日志: {log.RWText} - {log.RegAddr} - {log.Values} - {log.Operation}");
        }

        private void OnError(string error)
        {
            Console.WriteLine($"[EVENT] 错误: {error}");
        }

        private void OnStatusChanged(string status)
        {
            Console.WriteLine($"[EVENT] 状态: {status}");
        }
        #endregion

        #region 日志捕获相关方法

        /// <summary>
        /// 开始日志捕获
        /// </summary>
        public bool StartLogcat()
        {
            Console.WriteLine($"[AdbService] 开始日志捕获");
            return _logcatService.StartCapture();
        }

        /// <summary>
        /// 停止日志捕获
        /// </summary>
        public bool StopLogcat()
        {
            Console.WriteLine($"[AdbService] 停止日志捕获");
            return _logcatService.StopCapture();
        }

        /// <summary>
        /// 重启日志捕获
        /// </summary>
        public void RestartLogcat()
        {
            Console.WriteLine($"[AdbService] 重启日志捕获");
            _logcatService.RestartCapture();
        }

        /// <summary>
        /// 获取日志数据
        /// </summary>
        public List<LogcatModel> GetLogcatData()
        {
            return _logcatService.GetLogs();
        }

        /// <summary>
        /// 获取最新的日志数据（指定数量）
        /// </summary>
        public List<LogcatModel> GetRecentLogcatData(int count)
        {
            return _logcatService.GetRecentLogs(count);
        }

        /// <summary>
        /// 清空日志数据
        /// </summary>
        public void ClearLogcatData()
        {
            _logcatService.ClearLogs();
        }

        /// <summary>
        /// 检查日志捕获状态
        /// </summary>
        public bool IsLogcatRunning
        {
            get { return _logcatService.IsRunning; }
        }

        #endregion

        #region 寄存器操作相关方法

        /// <summary>
        /// 执行寄存器读操作 - 优化版本
        /// </summary>
        public string ReadRegister(string address, string id = "0")
        {
            Console.WriteLine($"[AdbService] 读取寄存器: {address}, ID: {id}");

            // 在调试模式下，无法自动获取日志，返回提示信息
            if (_logcatService._isDebugMode)
            {
                Console.WriteLine($"[AdbService] 调试模式下无法自动获取寄存器值，请查看CMD窗口中的日志输出");
                EnableDebugMode();
                string command1 = $"{_commandR} \"0,{address.Replace(" ", "")},0,{id}\"";
                ExecuteRegisterCommand(command1);
                return "调试模式：请查看CMD窗口中的日志输出";
            }

            EnableDebugMode();

            // 确保日志捕获服务运行
            if (!IsLogcatRunning)
            {
                Console.WriteLine($"[AdbService] 启动日志捕获服务");
                StartLogcat();
                // 给日志服务一点时间启动
                Thread.Sleep(2000);
            }

            // 清空之前的日志，避免旧数据干扰
            ClearLogcatData();
            Console.WriteLine($"[AdbService] 已清空旧日志数据");

            // 发送读取命令
            string command = $"{_commandR} \"0,{address.Replace(" ", "")},0,{id}\"";
            Console.WriteLine($"[AdbService] 发送寄存器读取命令");
            ExecuteRegisterCommand(command);

            _isWant = true;
            DateTime startTime = DateTime.Now;
            TimeSpan timeout = TimeSpan.FromSeconds(15); // 15秒超时

            int checkCount = 0;
            while (_isWant && (DateTime.Now - startTime) < timeout)
            {
                checkCount++;
                var logs = _logcatService.GetLogs();

                if (logs.Count == 0)
                {
                    if (checkCount % 100 == 0) // 每100次检查输出一次状态
                    {
                        Console.WriteLine($"[AdbService] 等待日志中... 已等待 {(DateTime.Now - startTime).TotalSeconds:F1} 秒");
                    }
                    Thread.Sleep(10);
                    continue;
                }

                // 查找匹配的寄存器读取日志
                var lastRead = logs.FindLast(c =>
                    c.RWText == "RegRead" && c.RegAddr.Equals(address, StringComparison.OrdinalIgnoreCase));

                if (lastRead != null)
                {
                    _isWant = false;
                    Console.WriteLine($"[AdbService] 读取寄存器成功: {address} = {lastRead.Values} (等待时间: {(DateTime.Now - startTime).TotalSeconds:F2}秒)");
                    return lastRead.Values;
                }

                // 输出一些调试信息
                if (checkCount % 50 == 0 && logs.Count > 0)
                {
                    var recentLogs = _logcatService.GetRecentLogs(3);
                    Console.WriteLine($"[AdbService] 最近收到的日志:");
                    foreach (var log in recentLogs)
                    {
                        Console.WriteLine($"[AdbService]   - {log.RWText} {log.RegAddr} = {log.Values} ({log.Operation})");
                    }
                }

                Thread.Sleep(10);
            }

            // 超时后检查是否有任何日志
            var allLogs = _logcatService.GetLogs();
            if (allLogs.Count > 0)
            {
                Console.WriteLine($"[AdbService] 超时! 但收到了 {allLogs.Count} 条日志，最后几条:");
                var recent = _logcatService.GetRecentLogs(5);
                foreach (var log in recent)
                {
                    Console.WriteLine($"[AdbService]   - {log.RWText} {log.RegAddr} = {log.Values} ({log.Operation})");
                }
            }
            else
            {
                Console.WriteLine($"[AdbService] 超时! 没有收到任何日志");
            }

            Console.WriteLine($"[AdbService] 读取寄存器超时: {address}");
            return "0";
        }

        /// <summary>
        /// 执行寄存器写操作 - 优化版本
        /// </summary>
        public string WriteRegister(string address, string value, string id = "0")
        {
            Console.WriteLine($"[AdbService] 写入寄存器: {address} = {value}, ID: {id}");


            EnableDebugMode();

            // 对于写入操作，我们不需要等待日志响应，直接发送命令即可
            var  command = $"{_commandR} \"1,{address.Replace(" ", "")},{value},{id}\"";
            var result = ExecuteRegisterCommand(command);
            Console.WriteLine($"[AdbService] 写入寄存器完成");
            return result;
        }

        /// <summary>
        /// 执行 I2C 读操作
        /// </summary>
        public string ReadI2C(string address, string id)
        {
            Console.WriteLine($"[AdbService] 读取I2C: {address}, ID: {id}");
            EnableDebugMode();

            if (!IsLogcatRunning)
            {
                StartLogcat();
            }

            string command = $"{_commandR} \"2,{address.Replace(" ", "")},0,{id}\"";
            ExecuteCommand(command);

            _isWant = true;
            DateTime startTime = DateTime.Now;
            TimeSpan timeout = TimeSpan.FromSeconds(10); // 10秒超时

            while (_isWant && (DateTime.Now - startTime) < timeout)
            {
                var logs = _logcatService.GetLogs();
                if (logs.Count == 0)
                {
                    Thread.Sleep(10);
                    continue;
                }

                var lastRead = logs.FindLast(c =>
                    c.RWText == "I2CRead" && c.RegAddr.Equals(address, StringComparison.OrdinalIgnoreCase));

                if (lastRead != null)
                {
                    _isWant = false;
                    Console.WriteLine($"[AdbService] 读取I2C成功: {address} = {lastRead.Values}");
                    return lastRead.Values;
                }

                Thread.Sleep(1);
            }

            Console.WriteLine($"[AdbService] 读取I2C超时: {address}");
            return "0";
        }

        /// <summary>
        /// 执行 I2C 写操作
        /// </summary>
        public string WriteI2C(string address, string value, string id)
        {
            Console.WriteLine($"[AdbService] 写入I2C: {address} = {value}, ID: {id}");
            EnableDebugMode();
            string command = $"{_commandR} \"3,{address.Replace(" ", "")},{value},{id}\"";
            string result = ExecuteCommand(command);
            Console.WriteLine($"[AdbService] 写入I2C结果: {result}");
            return result;
        }
        #endregion

        #region 设备管理相关方法

        /// <summary>
        /// 开启调试模式
        /// </summary>
        public string EnableDebugMode()
        {
            Console.WriteLine($"[AdbService] 开启调试模式");
            return ExecuteCommand(_commandMainSwitchS);
        }

        /// <summary>
        /// 关闭调试模式
        /// </summary>
        public string DisableDebugMode()
        {
            Console.WriteLine($"[AdbService] 关闭调试模式");
            return ExecuteCommand(_commandMainSwitchE);
        }
        /// <summary>
        /// 专门用于寄存器命令的执行
        /// </summary>
        private string ExecuteRegisterCommand(string command)
        {
            Console.WriteLine($"[AdbService] 执行寄存器命令: '{command}'");
            return CmdUtils.ExecuteRegisterCommand(command, _adbPath, false);
        }
        /// <summary>
        /// 执行命令
        /// </summary>
        public string ExecuteCommand(string command)
        {
            Console.WriteLine($"[AdbService] 执行命令: {command}");
            string result = CmdUtils.ExecuteRegisterCommand(command, _adbPath,true);
            Console.WriteLine($"[AdbService] 命令结果: {result}");
            return result;
        }

        /// <summary>
        /// 关闭所有 ADB 进程
        /// </summary>
        public void CloseAdb()
        {
            try
            {
                Console.WriteLine($"[AdbService] 关闭所有ADB进程");
                ProcessStartInfo psi = new ProcessStartInfo
                {
                    FileName = "taskkill",
                    Arguments = "/F /IM adb.exe",
                    WindowStyle = ProcessWindowStyle.Hidden,
                    UseShellExecute = true
                };
                Process.Start(psi);
                Thread.Sleep(500);
                Console.WriteLine($"[AdbService] ADB进程已关闭");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[AdbService] 关闭ADB时出错: {ex.Message}");
            }
        }

        /// <summary>
        /// 检查设备是否连接
        /// </summary>
        public bool CheckDeviceConnected(out List<string> devices)
        {
            Console.WriteLine($"[AdbService] 检查设备连接状态");
            devices = new List<string>();
            try
            {
                string result = ExecuteCommand("adb devices");
                var lines = result.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);

                foreach (var line in lines)
                {
                    // 跳过标题行和空行
                    if (string.IsNullOrWhiteSpace(line) || line.Contains("List of devices"))
                        continue;

                    // 按制表符分割行
                    var parts = line.Split(new[] { '\t' }, StringSplitOptions.RemoveEmptyEntries);
                    if (parts.Length >= 2 && parts[1].Trim().Equals("device", StringComparison.OrdinalIgnoreCase))
                    {
                        devices.Add(parts[0].Trim());
                    }
                }

                Console.WriteLine($"[AdbService] 找到 {devices.Count} 个设备");
                return devices.Count > 0;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[AdbService] 检查设备连接时出错: {ex.Message}");
                return false;
            }
        }

        /// <summary>
        /// 重启 ADB 服务
        /// </summary>
        public void RestartAdbServer()
        {
            try
            {
                Console.WriteLine($"[AdbService] 重启ADB服务");
                // 先停止日志捕获
                if (IsLogcatRunning)
                {
                    StopLogcat();
                }

                ExecuteCommand("adb kill-server");
                Thread.Sleep(500);
                ExecuteCommand("adb start-server");
                Thread.Sleep(1000);
                Console.WriteLine($"[AdbService] ADB服务重启完成");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[AdbService] 重启ADB服务时出错: {ex.Message}");
            }
        }

        /// <summary>
        /// 设置设备为TCP/IP模式
        /// </summary>
        public bool SetTcpipMode(string deviceId, int port = 5555)
        {
            try
            {
                Console.WriteLine($"[AdbService] 设置设备 {deviceId} 为TCP/IP模式，端口: {port}");
                string command = $"adb -s {deviceId} tcpip {port}";
                string result = ExecuteCommand(command);

                // 检查是否成功
                bool success = result.Contains("restarting in TCP mode") ||
                       result.Contains("restarting in TCP mode port");

                Console.WriteLine($"[AdbService] 设置TCP/IP模式{(success ? "成功" : "失败")}");
                return success;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[AdbService] 设置TCP/IP模式失败: {ex.Message}");
                throw new Exception($"设置TCP/IP模式失败: {ex.Message}", ex);
            }
        }

        /// <summary>
        /// 断开TCP/IP连接
        /// </summary>
        public bool DisconnectDevice(string ipAddress, int port = 5555)
        {
            try
            {
                Console.WriteLine($"[AdbService] 断开设备连接: {ipAddress}:{port}");
                string command = $"disconnect {ipAddress}:{port}";
                string result = ExecuteCommand(command);
                Console.WriteLine($"[AdbService] 设备连接已断开");
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[AdbService] 断开连接失败: {ex.Message}");
                throw new Exception($"断开连接失败: {ex.Message}", ex);
            }
        }

        /// <summary>
        /// 通过TCP/IP连接设备
        /// </summary>
        public bool ConnectToDevice(string ipAddress, int port = 5555)
        {
            try
            {
                Console.WriteLine($"[AdbService] 连接设备: {ipAddress}:{port}");
                string command = $"adb connect {ipAddress}:{port}";
                string result = ExecuteCommand(command);

                // 检查连接结果
                bool success = result.Contains("connected to") ||
                       result.Contains("already connected");

                Console.WriteLine($"[AdbService] 连接设备{(success ? "成功" : "失败")}");
                return success;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[AdbService] 连接设备失败: {ex.Message}");
                throw new Exception($"连接设备失败: {ex.Message}", ex);
            }
        }

        /// <summary>
        /// 检查特定设备的连接状态
        /// </summary>
        public bool CheckDeviceConnectionStatus(string deviceId)
        {
            Console.WriteLine($"[AdbService] 检查设备连接状态: {deviceId}");
            if (string.IsNullOrEmpty(deviceId))
            {
                Console.WriteLine($"[AdbService] 设备ID为空");
                return false;
            }

            try
            {
                // 执行一个简单的命令来验证设备是否真正可用
                string result = ExecuteCommand($"adb connect {deviceId}");
                bool connected = result.Contains("connected");
                Console.WriteLine($"[AdbService] 设备 {deviceId} 连接状态: {(connected ? "已连接" : "未连接")}");
                return connected;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[AdbService] 检查设备连接状态时出错: {ex.Message}");
                return false;
            }
        }

        #endregion

        public void Dispose()
        {
            _logcatService?.Dispose();
        }
    }
}